package pl.edu.agh.inpema.components.resultsSerializer.fileSerializer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import pl.edu.agh.inpema.core.model.GlobalResultsSerializer;
import pl.edu.agh.inpema.core.model.ProfilePair;
import pl.edu.agh.inpema.core.model.globalAnalyzer.GlobalAnalyzeResult;

public class FileResultsSerializer implements GlobalResultsSerializer {

	private String fileName;
	private String separator;
	
	private static final Logger logger = Logger.getLogger(FileResultsSerializer.class);
	
	public FileResultsSerializer() {
		
	}
	
	public FileResultsSerializer(String fileName, String separator) {
		this.fileName = fileName;
		this.separator = separator;
	}
	
	public void serialyzeResults(GlobalAnalyzeResult results) {
		File file = new File(this.fileName);
		try {
			file.createNewFile();
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			
			List<String> analyzersList = new LinkedList<String>();
			analyzersList.addAll(results.getAnalyzers());
			Collections.sort(analyzersList);
			
			writer.write("Profile1"+separator+"Profile2");
			for (String analyzerName : analyzersList)
				writer.write(separator+analyzerName);
			writer.write("\n");
			
			
			Set<ProfilePair> profilePairsSet = new HashSet<ProfilePair>();
			for (String analyzerName : analyzersList) {
				profilePairsSet.addAll(results.getAnalyzerResults(analyzerName).getAllProfilePairs());
			}
			List<ProfilePair> profilePairsList = new LinkedList<ProfilePair>();
			profilePairsList.addAll(profilePairsSet);
			Collections.sort(profilePairsList);
			
			for (ProfilePair pair : profilePairsList) {
				writer.write(pair.getProfile1()+separator+pair.getProfile2());
				
				for (String analyzerName : analyzersList) {
					writer.write(separator);
					Integer i = results.getAnalyzerResults(analyzerName).getValue(pair);
					if (i == null)
						writer.write("-");
					else
						writer.write(i.toString());
				}
				
				writer.write("\n");
			}
			
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public void setSeparator(String separator) {
		this.separator = separator;
	}
	
}
